package com.xiaohong.security.service;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;

/**
 * @author : xiaohong
 * @date : 2021/4/29 19:56
 * 判断用户是否有指定路径的访问权限
 */
@Service
public class MyServiceImpl implements MyService {
    @Override
    public Boolean hasPerminssion(HttpServletRequest httpServletRequest, Authentication authentication) {
        Object principal = authentication.getPrincipal();
        // 判断是否是UserDetails对象
        if (principal instanceof UserDetails){
            UserDetails userDetails = (UserDetails) principal;
            Collection<? extends GrantedAuthority> authorities = userDetails.getAuthorities();
            return authorities.contains(new SimpleGrantedAuthority(httpServletRequest.getRequestURI()));
        }
        return false;
    }
}
